from . import home
from flask import render_template,request,url_for,session
from app.models import *
import os,json,time,random,re
import copy


# 请求处理之前的 装饰器
@home.before_request
def checklogin():
    # 获取当前的请求路径
    path = request.path
    # 要求登录才能请求的路径
    urllist = [url_for('home.createblog')]
    if path in urllist:
        # 判断是否登录
        if not session.get('VipUser',None):
                return '<script>alert("请先登录");location.href="'+url_for('home.login')+'?next='+path+'"</script>'


@home.route("/")
def index():
    # 获取所有的博文
    ps = copy.copy(Posts.query.all())
    return render_template('/home/index.html',posts = ps)


# 博文发布
@home.route('/create/blog/',methods=['GET','POST'])
def createblog():
    if request.method == 'GET':
        # 获取所有的标签
        tags = Tags.query.all()
        # 返回一个博文发布页面
        return render_template('/home/blogs/add.html',tags=tags)

    elif request.method == 'POST':
        # 执行博文的添加

        # 准备数据
        data = {}
        data['title'] = request.form.get('title')
        data['uid'] = session['VipUser']['uid']
        data['context'] = request.form.get('content')
        
        # 创建文章
        post = Posts(**data)
        # 给文章设置标签
        post.tags = list(map(lambda x:Tags.query.get(x),request.form.getlist('tags')))
        # 执行添加
        db.session.add(post)
        db.session.commit()
        return '<script>alert("发布成功");location.href="'+url_for('home.bloginfo',post_id=post.id)+'"</script>'


# 博文详情
@home.route('/blogs/<int:post_id>')
def bloginfo(post_id):
    # 根据post_id获取博文信息
    blog = Posts.query.get(post_id)
    return render_template('/home/bloginfo.html',blog=blog)


# 博文,用户,标签,搜索
@home.route('/blogs/search/')
def blogssearch():
    # 接受关键字
    keywords = request.args.get('keywords')
    # 按用户搜索
    users = User.query.filter(User.username.contains(keywords)).all()
    # 博文标题搜索
    blogs = Posts.query.filter(Posts.title.contains(keywords)).all()
    context = {'users':users,'blogs':blogs}
    return render_template('/home/blogs/search.html',**context)


# 博文列表 按用户
@home.route('/blogs/user/<int:uid>/')
def userblogs(uid):
    # 根据用户id获取当前用户的所有博文列表
    blogs = Posts.query.filter_by(uid=uid)
    return render_template('/home/blogs/userlist.html',blogs=blogs)


# 博文列表 按标签
@home.route('/blogs/tags/<int:tid>/')
def tagsblogs(tid):
    # 根据标签id获取标签
    tag = Tags.query.get(tid)
    return render_template('/home/blogs/taglist.html',tag=tag)


# 博文的评论
@home.route('/blogs/comments/',methods=['POST'])
def comments():
    # 获取数据
    data = {}
    # 获取当前博文对象
    ob = Posts.query.get(request.form['post_id'])
    # 判断当前是否为作者的评论
    if ob.uid == int(request.form['user_id']):
        data['reply'] = 0
    else:
        data['reply'] = 1
    # 是否为评论回复
    if request.form['cid']:
        # 回复
        data['cid'] = int(request.form['cid'])
    # 准备数据
    data['post_id']  = ob.id
    data['user_id']  = int(request.form['user_id'])
    data['context']  = request.form['context']
    # 执行评论的添加
    res = Comments(**data)
    db.session.add(res)
    db.session.commit()
    return '<script>alert("评论成功");location.href="'+url_for('home.bloginfo',post_id=ob.id)+'"</script>'


# 登录
@home.route("/login/",methods=['GET','POST'])
def login():
    nextpath = request.args.get('next','/')
    if request.method == 'GET':
        return render_template('/home/login/login.html')

    elif request.method == 'POST':

        # 先根据手机号获取用户
        ob = User.query.filter_by(phone=request.form['phone']).first()

        if ob != None:
            # 检测密码是否正确
            if ob.CheckPassword(request.form['password']):
                # 密码正确
                # 执行登录
                session['VipUser'] = {'uid':ob.id,'username':ob.username,'phone':ob.phone}
                return '<script>alert("欢迎登录");location.href="'+nextpath+'"</script>'
        return '<script>alert("用户名或密码错误");location.href="'+url_for('home.login')+'?next='+nextpath+'"</script>'


# 注册
@home.route("/register/",methods=['GET','POST'])
def register():
    if request.method == 'GET':
        return render_template('/home/login/register.html')

    elif request.method == 'POST':
        # 执行注册操作
        try:
            # 获取数据
            data = {}
            data['phone'] = request.form['phone']
            data['password'] = User.MD5password(request.form['password'])
            # 添加
            ob = User(**data)
            db.session.add(ob)
            db.session.commit()
            return '<script>alert("注册成功.欢迎登录");location.href="'+url_for('home.login')+'"</script>'

        except:
            return '<script>alert("注册失败");location.href="'+url_for('home.register')+'"</script>'


# 退出登录
@home.route('/logout/')
def logout():
    session.pop('VipUser')
    return '<script>alert("退出成功");location.href="'+url_for('home.index')+'"</script>'


# ueditor读取配置文件
@home.route('/ueditconfig/', methods=['GET', 'POST'])
def ueditconfig():
    # 导入地址
    from app import BASE_DIR
    # 获取请求动作
    action = request.args.get('action')
    result = {}
    # 读取配置文件
    if action == 'config':
    # 初始化时，返回配置文件给客户端
        with open(os.path.join(BASE_DIR,'static', 'ueditor', 'php',
                               'config.json')) as fp:
            try:
                # 删除 `/**/` 之间的注释
                CONFIG = json.loads(re.sub(r'\/\*.*\*\/', '', fp.read()))
            except:
                CONFIG = {}
        result = CONFIG
    # 文件上传
    if action  == 'uploadimage':
        upfile = request.files['upfile']  # 这个表单名称以配置文件为准
        # upfile 为 FileStorage 对象
        # 这里保存文件并返回相应的URL

        Suffix = upfile.filename.split('.').pop()
        filename = str(time.time())+str(random.randint(10000,99999))+'.'+Suffix
        imgurl = '/static/uploads/'+filename
        upfile.save(BASE_DIR+imgurl)

        result = {
            "state": "SUCCESS",
            "url": imgurl,
            "title": filename,
            "original":filename
        }

        print(BASE_DIR)

    return json.dumps(result)
